/**
 * 
 */
package cn.com.pansky.payment;
import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.com.pansky.util.AppUtils;
import cn.com.pansky.util.PayUtils;
import cn.com.pansky.util.RequestUtils;

import com.google.common.collect.Maps;
/**
 * 支付请求处理
 * 
 * @author 清算平台项目组
 * @version v1.0.1
 * @date 2013-04-17
 */
//获取请求参数
//转换编码
//定义接口数据集合
//定义接口参数
//生成签名
//构造请求数据表单
public class PaymentServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse resp)
		throws ServletException, IOException {
		
		//获取请求参数
		Map<String, String> reqMap = RequestUtils.getReqMap(request);
		
		//转换编码
		reqMap.put("merReserved1", new String(reqMap.get("merReserved1").getBytes("ISO8859-1"), reqMap.get("charset")));
		reqMap.put("merReserved2", new String(reqMap.get("merReserved2").getBytes("ISO8859-1"), reqMap.get("charset")));
		reqMap.put("merReserved3", new String(reqMap.get("merReserved3").getBytes("ISO8859-1"), reqMap.get("charset")));
		
		//定义接口数据集合
		Map<String, String> paramMap = Maps.newHashMap();
		
		//定义接口参数
		String[] paramKeys = new String[] { "version", "charset", "signMethod", "payType", "transType", "merId", "backEndUrl", "frontEndUrl", "orderTime", "orderNumber", "orderAmount", "orderCurrency", "defaultBankNumber", "customerIp",
				"merReserved1", "merReserved2", "merReserved3", "merSiteIP", "gateWay" };
		for (String item : paramKeys) {
			paramMap.put(item, reqMap.get(item));
		}
		
		//生成签名
		String sign = PayUtils.signDictionary(paramMap, paramKeys, reqMap.get("signKey"), reqMap.get("charset"));
		System.out.println("向清算平台发送支付请求:" + AppUtils.restMapToStr(paramMap));
		System.out.println("原始签名：" + sign);
		//构造请求数据表单
		StringBuffer formbuf = new StringBuffer();
		formbuf.append("\r\n<script language=\"javascript\">window.onload=function(){document.payform.submit();}</script>\r\n");
		formbuf.append("\r\n<form id='payform' name='payform' action='" + reqMap.get("payUrl") + "' method='POST'>\r\n");
		for (String item : paramKeys) {
			formbuf.append("\t<input type='hidden' name='" + item + "' value='" + paramMap.get(item) + "' />\r\n");
		}
		formbuf.append("\t<input type='hidden' name='sign' value='" + sign + "' />\r\n");
		formbuf.append("</form>\r\n");
		resp.setContentType("text/html;charset=" + reqMap.get("charset"));
		resp.setCharacterEncoding(reqMap.get("charset"));
		try {
			resp.getWriter().write(formbuf.toString().replace('\'', '"'));
		} catch (IOException e) {
			System.out.println("支付失败");
		}
	}
}
